<?php
plugin('add-external-link-top');
if($_POST['deleteid']) {
	$sql = "DELETE FROM ".DBTABLEPREFIX."content_pages WHERE id = '".$_POST['deleteid']."'";
	$query = $admin->db->query($sql) or die($admin->db->error());
	echo $admin->message('success', 'Link Deleted!', 'Your external link has been successfully deleted');
	exit();
}
if($_POST['addURL']) {
	if(empty($_POST['url'])) {
		$messages .= $admin->message('error', "Don't leave field blank!", "You left the URL field blank. It is imperative that you fill it now.");
	}
	else {
		$parent = explode('-', $_POST['pos']);
		$parent_cat = ($parent[0] == 's' ? 'yes' : '');
		$parent_id = $parent[1];
		$ser = serialize(array('show'=>'show','external'=> htmlentities($_POST['url'], ENT_QUOTES, 'UTF-8')));
		$sql = "INSERT INTO ".DBTABLEPREFIX."content_pages
			(id,title,content,orderingid,menutitle,parent_id,time,secondary,options) VALUES
			('','','','".$_POST['weg']."','".sanitize_sql_string($_POST['menuTitle'])."','".$parent_id."','".time()."','".$parent_cat."','".$ser."')";
		$query = $admin->db_query($sql) or die($admin->db->error());
		if($query)
			$messages .= $admin->message('success', 'Link Added', 'Your external link was added.');
		else
			$messages .= $admin->message('error', 'Link NOT Added', 'Something went wrong with the database!');
	}
}
if($_GET['id']) {
	if($_POST['updateURL']) {
		if(empty($_POST['url'])) {
			$messages .= $admin->message('error', "Don't leave field blank!", "You left the URL field blank. It is imperative that you fill it now.");
		}
		else {
			$parent = explode('-', $_POST['pos']);
			$parent_cat = ($parent[0] == 's' ? 'yes' : '');
			$parent_id = $parent[1];
		$ser = serialize(array('show'=>'show','external'=> htmlentities($_POST['url'], ENT_QUOTES, 'UTF-8')));
			$sql = "UPDATE ".DBTABLEPREFIX."content_pages SET
				orderingid= '{$_POST['weg']}',
				menutitle = '".sanitize_sql_string($_POST['menuTitle'])."',
				parent_id= '{$parent_id}',
				time='".time()."',
				secondary='{$parent_cat}',
				options='{$ser}' WHERE id = '{$_GET['id']}'";
			$query = $admin->db_query($sql) or die($admin->db->error());
			if($query)
				$messages .= $admin->message('success', 'Link Updated', 'Your external link was updated.');
			else
				$messages .= $admin->message('error', 'Link NOT Added', 'Something went wrong with the database!');
		}	
	}
	$id=$_GET['id'];
	$list = $theme->buildNavArray();
	$secondary_list = $theme->arraySecondaryNavigation();
	$list = $theme->buildNavArray();
	$sql = "SELECT * FROM ".DBTABLEPREFIX."content_pages WHERE id = '$id' LIMIT 1";
	$content = $admin->db_query($sql) or die($admin->db->error());
	$count = $admin->db->numRows($content);
	if($count == "1") {
		$row = $admin->db->fetchAssoc($content);
			foreach($row as &$value)
				stripcslashes($value);
			$options = unserialize(stripcslashes($row['options']));
			$menutitle = htmlentities($row['menutitle'], ENT_QUOTES, 'UTF-8');
			$url = $options['external'];
			
			for($col = -20; $col <= 20; $col++) {
				$weight .= "\t<option value='$col'";
				if($col == $row['orderingid']) {
					$weight .= " selected='selected'";
				}
				$weight .= ">$col</option>\n";
			}
			$main = $theme->optionListFromArray($list, "p-", $row['parent_id']);
			$seco = $theme->optionListFromArray($secondary_list, "s-", $row['parent_id']);
			if($row['secondary'] == 'yes') {
				if(substr_count('selected=', $seco) > 0) {
					$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
				}
				else {
					$seco = '<option value="s-0" selected="selected">None (Secondary Menu Root Item)</option>'.$seco;
				}
			}
			else {
				if(substr_count('selected=', $main) > 0) {
					$main = '<option value="p-0">None (Root Item)</option>'.$main;
				}
				else {
					$main = '<option value="p-0" selected="selected">None (Main Menu Root Item)</option>'.$main;
				}
				$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
			}
	}
$add = <<<EOT
<form action='{$admin->current_page}' method='post'><fieldset>
<h2>Edit a External Link</h2>
<div class='form-row'>
	<label for='menuTitle'>Menu Title<span class="small gray">for example: Google</span></label>
	<span>
		<input type="text" name="menuTitle" value="{$menutitle}" />
	</span>
</div>
<div class='form-row'>
	<label for='url'>URL<span class="small gray">for example: http://www.google.com</span></label>
	<span>
		<input type="text" name="url" value="{$url}" />
	</span>
</div>
<div class='form-row'>
	<label for='pos'>Parent Item</label>
	<span>
		<select name="pos">
			<optgroup label="Main Menu">
				$main
			</optgroup>
			<optgroup label="Secondary Optional Menu">
				$seco
			</optgroup>
		</select>
	</span>
</div>
<div class='form-row'>
	<label for='weg'>Weight</label>
	<span>
		<select name="weg">
			$weight
		</select>
	</span>
</div>
<div class='form-row form-row-last'>
	<label for='updateURL'>Update</label>
	<span>
		<input type="submit" name="updateURL" value="Go!" />
	</span>
</div>
</fieldset>
</form>
EOT;
}
$DBTABLEPREFIX = DBTABLEPREFIX;
$sql = <<<EOT
SELECT * FROM {$DBTABLEPREFIX}content_pages WHERE options LIKE '%s:8:"external"%'
EOT;
$query = $admin->db->query($sql) or die($admin->db->error());
//var_dump($query);
////$num = $admin->db->numRows()
while($row = $admin->db->fetchAssoc($query)) {
	//var_dump($row);
	$secondary = ($row['secondary'] == 'yes' ? 'yes' : 'no');
	$options = unserialize($row['options']);
	foreach($row as $key=>$value) {
		$row[$key] = stripcslashes($value);
	}
	$parent = $admin->idLookup($row['parent_id']);
	$rows .= <<<EOT
			<tr>
				<td>{$row['id']}</td>
				<td>{$secondary}</td>
				<td>{$row['menutitle']}</td>
				<td>{$options['external']}</td>
				<td>{$parent}</td>
				<td>{$row['orderingid']}</td>
				<td>
					<a href="{$admin->current_page}&id={$row['id']}" class="externalEdit helplink" title="Edit this link!">
						<img src="includes/admin/images/icons/edit-16x16.png" alt="Edit this link!"/>
					</a>
					<a href="{$admin->current_page}&id={$row['id']}" name='{$row['id']}' class="deleteExternal helplink" title="Delete this link!">
						<img src="includes/admin/images/icons/delete-16x16.png" alt="Delete this link!"/>
					</a>
				</td>
			</tr>

EOT;
}
$currlinks .= <<<EOT
<fieldset>
	<h2>Current External Links</h2>
	<table id="current_external_links">
		<thead>
			<tr>
				<th>Page ID</th>
				<th>Secondary</th>
				<th>Menu Title</th>
				<th>URL</th>
				<th>Parent Item</th>
				<th>Weight</th>
				<th>Edit</th>
			</tr>
		</thead>
		<tbody>
			{$rows}
		</tbody>
	</table><br/>
</fieldset>
EOT;
//$currlinks = var_dump($nr);
	$list = $theme->buildNavArray();
	$secondary_list = $theme->arraySecondaryNavigation();
	for($col = -20; $col <= 20; $col++) {
		$weight .= "\t<option value='$col'";
		if($col == $_POST['weight']) {
			$weight .= " selected='selected'";
		}
		$weight .= ">$col</option>\n";
	}
			$main = $theme->optionListFromArray($list, "p-", $parent_id);
			$seco = $theme->optionListFromArray($secondary_list, "s-", $parent_id);
			if($row['secondary'] == 'yes') {
				if(substr_count('selected=', $seco) > 0) {
					$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
				}
				else {
					$seco = '<option value="s-0" selected="selected">None (Secondary Menu Root Item)</option>'.$seco;
				}
			}
			else {
				if(substr_count('selected=', $main) > 0) {
					$main = '<option value="p-0">None (Root Item)</option>'.$main;
				}
				else {
					$main = '<option value="p-0" selected="selected">None (Main Menu Root Item)</option>'.$main;
				}
				$seco = '<option value="s-0">None (Secondary Menu Root Item)</option>'.$seco;
			}
$form = <<<EOT
<form action='admin.php?page=manage-add-external-links' method='post'><fieldset>
<h2>Add a External Link</h2>
<div class='form-row'>
	<label for='menuTitle'>Menu Title<span class="small gray">for example: Google</span></label>
	<span>
		<input type="text" name="menuTitle" />
	</span>
</div>
<div class='form-row'>
	<label for='url'>URL<span class="small gray">for example: http://www.google.com</span></label>
	<span>
		<input type="text" name="url" />
	</span>
</div>
<div class='form-row'>
	<label for='pos'>Parent Item</label>
	<span>
		<select name="pos">
			<optgroup label="Main Menu">
				$main
			</optgroup>
			<optgroup label="Secondary Optional Menu">
				$seco
			</optgroup>
		</select>
	</span>
</div>
<div class='form-row'>
	<label for='weg'>Weight</label>
	<span>
		<select name="weg">
			$weight
		</select>
	</span>
</div>
<div class='form-row form-row-last'>
	<label for='addURL'>Add</label>
	<span>
		<input type="submit" name="addURL" value="Go!" />
	</span>
</div>
</fieldset>
</form>
EOT;

$admin->page_info['content']['page_title'] = "Add/Edit External Link";
$admin->page_info['content']['page_content']	= $messages.$add.$currlinks.$form;
plugin('add-external-link-bottom');
//Display page
include(BASE_URL.'includes/admin/admin.php');
?>